from datetime import datetime

from django.contrib import auth
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from application.models import User, Org
from django.core import serializers
from application.utils.model_utils import to_json, to_page, result
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.sessions.models import Session
import random, json, cv2, string,  numpy as np
from application.settings import DEBUG
from application.utils.regular import CheckRegulary, userRule
from django.db import transaction


def getImg(request: WSGIRequest):
    """
        认证码
    """
    width=130
    height=50
    chars=string.ascii_uppercase + string.ascii_lowercase + string.digits
    count=4
    # 生成随机验证码
    captcha_text = ''.join([random.choice(chars) for _ in range(count)])
    request.session['checkCode'] = captcha_text.lower()
    print(captcha_text.lower())
    request.session.save()
    # 创建空白图像
    image = np.zeros((height, width, 3), np.uint8)
    image.fill(255)  # 使用白色背景
    # 设置文本属性
    font_face = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 1
    color = (20, 80, 0)
    thickness = 1
    p = random.randint(5,20)
    for i in captcha_text:
        # 在图像上绘制文本
        cv2.putText(image, i, (p, height//2 + 10), font_face, font_scale, color, 2)
        n = random.randint(20,30)
        p+=n

    # 添加噪声
    for i in range(30):
        x1= random.randint(0, 150) % 200
        y1= random.randint(0, 50) 
        x= random.randint(-1,1) 
        y= random.randint(-1,1) 
        cv2.line(image, (x1, y1), (x1+x, y1+y), color, 1)

    for i in range(8):
        x1= random.randint(0, 150) % 200
        y1= random.randint(0, 50) 
        x= random.randint(-15,15) 
        y= random.randint(-15,15) 
        cv2.line(image, (x1, y1), (x1+x, y1+y), color, 2)

    _, img = cv2.imencode('.png', image)
    return HttpResponse(img.tobytes(), content_type='image/png')

def login(request: WSGIRequest):
    """
        登录页
    """
    if(isinstance(request.user, User)):
        return HttpResponse(json.dumps({"status": "success"}), content_type="application/json") 
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        checkCode = request.session.get('checkCode') if DEBUG else request.POST.get("checkCode")
        
        if( DEBUG and (checkCode is None or checkCode.lower() != request.session.get('checkCode'))):
             return HttpResponse(json.dumps({"status": "fail", "msg": "认证码错误"}), content_type="application/json")
        user = User.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
                auth.login(request=request, user=user)
                return HttpResponse(json.dumps({"status": "success"}), content_type="application/json")
            else:
                return HttpResponse(json.dumps({"status": "fail","msg": "用户或密码错误"}), content_type="application/json")
        return HttpResponse(json.dumps({"status": "fail","msg": "用户或密码错误"}), content_type="application/json")
    return render(request, "login.html", locals())

def logout(request: WSGIRequest):
    """
    退出登录
    """
    auth.logout(request=request)
    return redirect("/login")

def get_logins(request: WSGIRequest):
    page_number = request.GET.get("page_index", 1)
    page_size = request.GET.get("page_size", 10)
    sessions = Session.objects.filter(expire_date__gte=datetime.now())
    user_ids = []
    for session in sessions:
        session_info = session.get_decoded()
        if session_info.get('_auth_user_id'):
            user_ids.append(session_info['_auth_user_id'])
    return HttpResponse(to_json(to_page(User.objects.filter(id__in=user_ids),page_number, page_size=page_size), "password"), content_type="application/json")

def index(request: WSGIRequest):
    return render(request,"index.html", locals())

def userAdd(request: WSGIRequest):
    u = User()
    body = request.POST
    check = CheckRegulary()
    for k in body:
        if userRule.get(k):
            if not check.check(userRule[k], body[k]):
                return HttpResponse(result(200, msg='字段: %s 格式不正确' % k),content_type="application/json")
        if k == 'org':
            if body[k]:
                orgs = json.loads(body[k])
        elif k == 'password':
            u.set_password(body[k])
        elif k == 'confirmPassword':
            continue
        else:
            setattr(u, k, body[k])
    try:
        transaction.atomic()
        u.save()
        if orgs:
                u.groups.set(orgs)
    except Exception as e:
        return HttpResponse(result(501, msg='保存失败'),content_type="application/json")
    return HttpResponse(result(200),content_type="application/json")

def delUser(request: WSGIRequest):
    user_id = request.GET['id']
    user = User.objects.filter(id=user_id)
    if user.delete()[0] == 1:
        return HttpResponse("ok", content_type="application/json")
    return HttpResponse("fail", content_type="application/json")

def users(request: WSGIRequest):
    org = request.GET.get('org')
    result = []
    users = User.objects.exclude(username=["admin", request.user.username])
    if org:
        users = users.filter(groups__id=org)
    else:
        users = users.filter(groups__id=None)
    for i in users.all():
        user = {}
        user['name'] = i.name
        user['username'] = i.username
        user['phone'] = i.phone
        user['password'] = ''
        user['email'] = i.email
        user['org'] = []
        user['date_joined'] = i.date_joined
        user['last_login'] = i.last_login
        result.append(user)
    return HttpResponse(to_json(result), content_type="application/json")
    

def android(request: WSGIRequest):
    return HttpResponse("ok", content_type="application/json")

def get_org(request: WSGIRequest):
    return HttpResponse(to_json(Org.objects.all(),"group_ptr_id"), content_type="application/json")

def orgAdd(request: WSGIRequest):
    name = request.POST["name"]
    parent = request.POST["parent"]
    if name and parent:
        org = Org()
        if(int(parent) > 0):
            org.pid = parent
        org.name = name
        org.save()
        return HttpResponse(result(200),content_type="application/json")
    return HttpResponse(result(300,msg="参数错误") ,content_type="application/json")

def orgDel(request: WSGIRequest):
    id = request.GET.get("id")
    if(Org.objects.filter(pid=id).count() > 0):
        return HttpResponse(result(-1, msg="存在子节点无法删除"),content_type="application/json") 
    else:
        org = Org.objects.filter(id=id)
        if org:
            org.delete()
    return HttpResponse(result(200),content_type="application/json")

def orgChangeName(request: WSGIRequest):
    id = request.POST.get("id")
    name = request.POST.get("label")
    if id and name:
        org = Org.objects.filter(id=id).first()
        org.name = name
        org.save()
        return HttpResponse(result(200),content_type="application/json")
    return HttpResponse(result(-1, msg="参数错误"),content_type="application/json") 

def orgMove(request: WSGIRequest):
    id = request.POST.get("id")
    pid = request.POST.get("pid")
    if id and pid:
        org = Org.objects.filter(id=id).first()
        if org:
            org.pid = pid
            org.save()
            return HttpResponse(result(200),content_type="application/json")
    return HttpResponse(result(-1, msg="参数错误"),content_type="application/json") 